package com.genia.toolbox.basics.tools.crypto.symmetric;

import java.io.IOException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.genia.toolbox.basics.tools.crypto.Encrypter;

/**
 *
 * This class is a part of a design pattern template.
 * This class is used to encrypt and decipher in Base64 encryption algorithm.
 *
 */
public class Base64 extends Encrypter {

	/**
	 * base64Encoder instance.
	 */
	private static BASE64Encoder base64Encoder = null;

	/**
	 * base64Decoder instance.
	 */
	private static BASE64Decoder base64Decoder = null;

	/**
	 * Constructor empty.
	 */
	public Base64(){
	}

	/**
	 * get an Base64Decoder instance
	 * @return
	 * 		Base64Decode instance
	 */
	private static BASE64Decoder getBase64Decoder() {
		if(base64Decoder == null)
			base64Decoder = new BASE64Decoder();
		return base64Decoder;
	}

	/**
	 * get an Base64Encoder instance
	 * @return
	 * 		Base64Encode instance
	 */
	private static BASE64Encoder getBase64Encoder() {
		if(base64Encoder == null)
			base64Encoder = new BASE64Encoder();
		return base64Encoder;
	}

	/**
	 * This method implement the Encrypter abstract method.
	 * It is used to decipher in a Base64 algorithm.
	 */
	@Override
	public String decryptAbstract(String decode) throws IOException {

		return new String(getBase64Decoder().decodeBuffer(decode));
	}

	/**
	 * This method implement the Encrypter abstract method.
	 * It is used to encrypt in a Base64 algorithm.
	 */
	@Override
	public String encryptAbstract(String encode) throws IOException {
		return getBase64Encoder().encode(encode.getBytes());
	}
}
